import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getLoginCode, getUserInfo, Login } from "../../service/modules/login";
interface LoginState {
  captcha: any;
  token: string;
  userInfo: any;
  code: number;
}
const initialState: LoginState = {
  token: "",
  code: 200,
  captcha: {},
  userInfo: {},
};
//验证码
export const fetchGetLoginCodeAction = createAsyncThunk(
  "login/captcha",
  async () => {
    const res = await getLoginCode();
    return res;
  }
);
export const fetchGetLoginAction = createAsyncThunk(
  "login/signin",
  async (params: {
    username: string;
    password: string;
    code: string;
    uuid: string;
  }) => {
    const res = await Login(params);
    // console.log(res);
    return res;
  }
);

export const fetchGetUserInfoAction = createAsyncThunk(
  "login/userInfo",
  async () => {
    const res = await getUserInfo();
    return res.user;
  }
);


const loginSlice = createSlice({
  name: "login",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchGetLoginCodeAction.fulfilled, (state, action) => {
        state.captcha = {
          img: action.payload.img,
          uuid: action.payload.uuid,
        };
      })
      .addCase(fetchGetLoginAction.fulfilled, (state, action) => {
        state.token = action.payload.token;
        state.code = action.payload.code;
      })
      .addCase(fetchGetUserInfoAction.fulfilled, (state, action) => {
        state.userInfo = action.payload;
      });
  },
});
// export const {} = loginSlice.actions;
export default loginSlice.reducer;
